/**
 * @author JackGao
 *			email:jackgao.china@gmail.com
 *  date：2016-6-23
 * 
 */
package cn.cuit.ds.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;


import org.springframework.stereotype.Repository;

import cn.cuit.ds.dao.IAddressDao;
import cn.cuit.ds.domain.Address;
import cn.cuit.ds.domain.User;
import cn.cuit.ds.utils.JdbcUtils;


@Repository(value="AddressDao")
public class AddressDao implements IAddressDao {

	public void add(Address address) {
		QueryRunner runner = JdbcUtils.getQueryRunner();
		String sql = "insert into address values(?,?,0,?,?,?)";
		try {
			runner.update(sql, address.getUserId(),address.getAddressId(),
					address.getRealName(),address.getAddress(),
					address.getPhone());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public List<Address> getAllByUserId(String userId) {
		QueryRunner runner = JdbcUtils.getQueryRunner();
		String sql = "select * from address where userId = ? and detail !=1";
		try {
			return runner.query(sql,new BeanListHandler<Address>(Address.class),userId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}



	public void deleteByAddressId(String addressId) {
		QueryRunner runner = JdbcUtils.getQueryRunner();
		String sql = "update address set detail=1 where addressId =?";
		try {
			runner.update(sql,addressId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}


	public void update(Address address) {
		QueryRunner runner = JdbcUtils.getQueryRunner();
		String sql = "UPDATE address set realName =?,phone=?,address=?,detail=0 where addressId=? AND userId=?";
		try {
			runner.update(sql,address.getRealName(),address.getPhone(),
					address.getAddress(),address.getAddressId(),
					address.getUserId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public Address getById(String addressId) {
		QueryRunner runner = JdbcUtils.getQueryRunner();
		String sql="select * from address where addressId =?";
		try {
			return runner.query(sql,new BeanHandler<Address>(Address.class),addressId);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}


}
